<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta charset="UTF-8">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <%@ include file="/common/client/header.jsp" %>
    <script src="${ctx}/statics/js/manager/manager.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

</head>
<body>
<%@ include file="/common/manager/searchBar.jsp" %>
<!--End Header End-->
<div class="i_bg bg_color">
    <!--Begin 用户中心 Begin -->
    <div class="m_content">
        <%@ include file="/common/manager/leftBar.jsp" %>
        <div class="m_right" id="content">
            <div class="mem_tit">
                添加商品/修改商品
            </div>

            <br>
            <table border="0" class="add_tab" style="width:930px;" cellspacing="0" cellpadding="0">
                <tr>
                    <td width="135" align="right">一级分类</td>
                    <td colspan="3" style="font-family:'宋体';">
                        <select name="classifyLevel1Id" style="background-color:#f6f6f6;" id="selectone">
                            <option value="" selected="selected">请选择...</option>

                        </select>
                    </td>
                </tr>
                <tr>
                    <td width="135" align="right">二级分类</td>
                    <td>
                        <select name="classifyLevel2Id" style="background-color:#f6f6f6;" id="selecttwo">
                            <option value="0" selected="selected">请选择...</option>

                        </select>
                    </td>
                </tr>
                <tr>
                    <td width="135" align="right">三级分类</td>
                    <td>
                        <select name="classifyLevel3Id" style="background-color:#f6f6f6;" id="classifyLevel3">
                            <option value="0" selected="selected">请选择...</option>

                        </select>
                    </td>
                </tr>
                <tr>
                    <td width="135" align="right">商品名称</td>
                    <td>
                        <input type="text" value="" class="add_ipt" name="goodsName" id="goodsName"/>（必填）

                    </td>
                </tr>
                <tr>
                    <td width="135" align="right">商品图片</td>
                    <td style="text-align: left;">

                        <input type="file" class="text" name="photo" id="fileInput" accept="image/*"/>
                        <div id="imagePreview" style="width: 100px; height: 50px; overflow: hidden;">
                        </div>
                        <button onclick="handleFile()">预览图片</button>


                    </td>
                </tr>
                <tr>
                    <td width="135" align="right">单价</td>
                    <td>
                        <input type="text" value="" class="add_ipt" name="price" id="price"/>
                    </td>
                </tr>
                <tr>
                    <td width="135" align="right">库存</td>
                    <td>
                        <input type="text" value="" class="add_ipt" name="stock" id="stock"/>
                    </td>
                </tr>
                <tr>
                    <td width="135" align="right">描述</td>
                    <td>
                        <textarea name="goodsDesc" id="goods_desc"></textarea>
                    </td>
                </tr>
                <tr>
                    <td></td>
                    <td id="dataone">

                    </td>
                </tr>
            </table>
        </div>
    </div>
    <%@ include file="/common/client/footer.jsp" %>
</div>
</body>

<script>
    //上传照片和预览照片
    function handleFile() {
        var fileInput = document.getElementById("fileInput");
        var imagePreview = document.getElementById("imagePreview");

        // 检查是否选择了文件
        if (fileInput.files.length > 0) {
            var file = fileInput.files[0];
            var reader = new FileReader();

            // 监听文件加载完成事件
            reader.onload = function (e) {
                var image = document.createElement("img");
                image.src = e.target.result;
                image.style.maxWidth = "100%";
                image.style.maxHeight = "100%";
                image.style.display = "block";
                imagePreview.innerHTML = ""; // 清空预览区域
                imagePreview.appendChild(image); // 将图片添加到预览区域
            };

            // 读取文件数据URL
            reader.readAsDataURL(file);
        } else {
            imagePreview.innerHTML = "没有选择文件";
        }
    }


    // 1. 在页面加载完成后执行的函数
    window.onload = function () {
        // 2. 获取 URL 参数中的 id
        var id = getId();

        if (id === null || id === undefined) {
            // 3. 如果 id 不存在或未定义，执行 onDocumentReady 函数，并显示"商品上架"按钮
            onDocumentReady();
            document.querySelector("#dataone").innerHTML = '<input type="button" value="商品上架" class="s_btn" onclick="myUpload()" id="updataone">';
        } else {
            // 4. 如果 id 存在，执行 selectClassify 函数，获取商品数据
            selectClassify(id, function (data) {
                console.log(data);
                // 在这里处理获取到的数据
            });
        }
    };

    // 5. 发起 AJAX 请求获取商品数据
    function selectClassify(id) {
        $.ajax({
            url: "/myselectgoodsservice?id=" + id,
            method: "GET",
            dataType: "json",
        }).done(function (data) {
            // 6. 处理获取到的商品数据
            disposeGoods(data);
        });
    };

    // 7. 处理商品数据
    function disposeGoods(data) {
        document.querySelector("#goodsName").value = data.goods_name;
        document.querySelector("#price").value = data.price;
        document.querySelector("#stock").value = data.stock;
        document.querySelector("#goods_desc").value = data.goods_desc;
        document.querySelector("#dataone").innerHTML = '<input type="button" value="确定修改" class="s_btn" onclick="myCorrect()" id="correctpne">';
        var imagePreview = document.getElementById("imagePreview");


        var imgElement = document.createElement("img");
        imgElement.src = "/files/" + data.file_name;
        imgElement.style.maxWidth = "100%";
        imgElement.style.maxHeight = "100%";
        imgElement.style.display = "block";

        imagePreview.appendChild(imgElement);


        if (data.classify_level3_id != 0) {
            selectGoods(data.classify_level3_id, "classifyLevel3");
            selectGoods(data.classify_level2_id, "selecttwo");
            selectGoods(data.classify_level1_id, "selectone");
        } else if (data.classify_level2_id != 0) {
            selectGoods(data.classify_level2_id, "selecttwo");
            selectGoods(data.classify_level1_id, "selectone");
        } else if (data.classify_level1_id != 0) {
            selectGoods(data.classify_level1_id, "selectone");
        }
    }

    // 8. 发起 AJAX 请求获取分类数据
    function selectGoods(id, index) {
        // 第一个 AJAX 请求
        $.ajax({
            url: "/myselectclassifyservice?id=" + id,
            method: "GET",
            dataType: "json",
        }).done(function (data) {
            let html = "";
            html += '<option value="' + data.id + '" selected="selected" disabled="disabled">' + data.classify_name + '</option>';
            console.log(html);
            $("#" + index).html(html);
        });
    };

    // 9. 从 URL 中获取 id 参数
    function getId() {
        let query = window.location.search;
        var idValue = query.split('?id=')[1];
        console.log("url地址后的值" + query);
        console.log("idValue" + idValue);

        if (idValue === null) {
            return null;
        } else {

            return idValue;
        }
    };

    // 10. 处理商品修改操作
    function myCorrect() {
        var selectone = document.querySelector("#selectone").value;
        var selecttwo = document.querySelector("#selecttwo").value;
        var classifyLevel3 = document.querySelector("#classifyLevel3").value;
        var goodsName = document.querySelector("#goodsName").value;
        var price = document.querySelector("#price").value;
        var stock = document.querySelector("#stock").value;
        var goods_desc = document.querySelector("#goods_desc").value;
        var fileInput = document.getElementById("fileInput");
        var file;
        if (fileInput.files.length > 0) {
            file = fileInput.files[0];
        }

        if ((file === null || file === undefined) || (goodsName === null || goodsName === undefined || goodsName.trim() === "") || (price === null || price === undefined || price.trim() === "") || (stock === null || stock === undefined || stock.trim() === "")) {
            showMessage("商品名称、图片、价格和库存数量不可为空");
        } else if (isNaN(price) || parseFloat(price) < 0) {
            showMessage("商品价格不可负且必须是数字");
        } else if (isNaN(stock) || parseFloat(stock) < 0) {
            showMessage("库存数量不可负且必须是数字");
        } else {
            // 11. 发起 AJAX 请求执行商品修改
            $.ajax({
                url: "/myCorrect",
                method: "GET",
                data: {
                    selectone: selectone,
                    selecttwo: selecttwo,
                    classifyLevel3: classifyLevel3,
                    goodsName: goodsName,
                    price: price,
                    stock: stock,
                    goods_desc: goods_desc,
                    file: file.name
                },
                success: function (data) {
                    if (data == "true") {
                        showMessage("修改成功");
                    } else {
                        showMessage("修改失败");
                    }
                }
            })
            ;
        }
    }

    // 12. 处理商品上架操作
    function myUpload() {
        var selectone = document.querySelector("#selectone").value;
        var selecttwo = document.querySelector("#selecttwo").value;
        var classifyLevel3 = document.querySelector("#classifyLevel3").value;
        var goodsName = document.querySelector("#goodsName").value;
        var price = document.querySelector("#price").value;
        var stock = document.querySelector("#stock").value;
        var goods_desc = document.querySelector("#goods_desc").value;
        var fileInput = document.getElementById("fileInput");
        var file;
        if (fileInput.files.length > 0) {
            file = fileInput.files[0];
        }
        console.log(file);
        if ((file === null || file === undefined) || (goodsName === null || goodsName === undefined || goodsName.trim() === "") || (price === null || price === undefined || price.trim() === "") || (stock === null || stock === undefined || stock.trim() === "")) {
            showMessage("商品名称、图片、价格和库存数量不可为空");
        } else if (isNaN(price) || parseFloat(price) < 0) {
            showMessage("商品价格不可负且必须是数字");
        } else if (isNaN(stock) || parseFloat(stock) < 0) {
            showMessage("库存数量不可负且必须是数字");
        } else {
            // 验证通过，执行商品上架的 AJAX 请求
            $.ajax({
                url: "/myUpload",
                method: "GET",
                data: {
                    selectone: selectone,
                    selecttwo: selecttwo,
                    classifyLevel3: classifyLevel3,
                    goodsName: goodsName,
                    price: price,
                    stock: stock,
                    goods_desc: goods_desc,
                    file: file.name
                },
                success: function (data) {
                    if (data == "true") {
                        showMessage("上架成功");
                    } else {
                        showMessage("上架失败");
                    }
                }
            });
        }

    }

    // 14. 声明全局变量
    var dataAll;

    // 15. 在文档加载完成时执行的函数
    function onDocumentReady() {
        // 16. 发起第一个 AJAX 请求获取一级分类数据
        $.ajax({
            url: "/contendisplay?id=1",
            method: "GET"
        }).done(function (data) {
            dataAll = data;
            let html = "";
            // 17. 遍历数据生成一级分类的选项
            $.each(data, function (index, item) {
                if (item.type == 1) {
                    html += '<option value="' + item.id + '" selected="selected">' + item.classify_name + '</option>';
                }
            });

            $("#selectone").html(html);

            // 18. 执行第二个 AJAX 请求
            doSecondAjax();
        });
    };

    // 19. 处理第二个 AJAX 请求
    function doSecondAjax() {
        document.querySelector("#selectone").addEventListener("change", function () {
            var selectedValue = this.value;

            // 20. 发起第二个 AJAX 请求获取与所选一级分类相关的二级分类数据
            $.ajax({
                url: "/contendisplay?id=2&parent_id=" + selectedValue,
                method: "GET"
            }).done(function (data) {
                let html = "";
                // 21. 遍历数据生成二级分类的选项
                $.each(data, function (index, item) {
                    html += '<option value="' + item.id + '" >' + item.classify_name + '</option>';
                });
                $("#classifyLevel3").html('<option value="0" selected="selected">请选择...</option>');
                $("#selecttwo").html(html);

                // 22. 在第二个 Ajax 请求的 done 回调函数内执行第三个 Ajax 请求
                doThirdAjax();
            });
        });
    }

    // 23. 处理第三个 AJAX 请求
    function doThirdAjax() {


        document.querySelector("#selecttwo").addEventListener("change", function () {
            var value = this.value;
            $.ajax({
                url: "/contendisplay?id=3&parent_id=" + value,
                method: "GET"
            }).done(function (data) {
                let html = "";
                $.each(data, function (index, item) {
                    html += '<option value="' + item.id + '" >' + item.classify_name + '</option>';
                });
                $("#classifyLevel3").html(html);
            });
        });

    };

    // 25. 显示消息的函数
    function showMessage(message) {
        // 26. 在这里添加显示消息的逻辑，比如弹出提示框
        alert(message);
    }
    
</script>
</html>

